<template>
  <div v-loading="isVisualVappShowLoadingProgress && isLoading" class="chartMain dark" :style="boxBgColor">
    <div :id="`chartMain${chartId}`" class="layer-switching-3d">
      <div
        v-for="(item, index) in menuList"
        :key="index"
        class="layer-switching-item"
        :style="getCssStyle('layerItem')"
        :class="setClass(item)"
        :title="item.label"
        @click="handleClick(item)"
        @mouseenter="mouseenterMenu(item)"
        @mouseleave="mouseleaveMenu(item)"
      >
        <div class="layer-item-bg" :style="getCssStyle({ height: 80 })">
          <Icon :conf="getIconConf(item, index)" />
        </div>
        <div class="ellipsis">{{ item.label }}</div>
      </div>
    </div>
  </div>
</template>
<script>
import Icon from '@/components/common/icon/icon.vue';
import chartBase from '@/mixin/chart-base.js';
import emitComponentBase from '@/mixin/emit-component-base.js';
import dataModel from '@/models/panel-config-data.js';
import storage from '@/utils/ado-self/ado-storage';
import { EMIT_PARAMS_OBJ } from '@/utils/constant';
import config from './config/config';
import dfCssStyle from './config/cssStyle-default.js';
import EventBus from '@/event-bus/EventBus.js';
export default {
  components: {
    Icon,
  },
  mixins: [chartBase, emitComponentBase],
  emits: [],
  data() {
    const _config = JSON.parse(JSON.stringify(config.config.property));
    return {
      isLoading: false,
      orgConfig: [],
      config: null,
      ..._config,
      chartId: '',
      dfCssStyle,
      isMouseMenu: '',
      active: '',
    };
  },
  created() {
    this.orgConfig = config;
    this.config = JSON.parse(JSON.stringify(this.orgConfig));

    this.chartId = `${this.widgetInstanceId}_01`;
  },
  mounted() {
    this.onPageWidgetsMounted(() => {
      this.componentStatusReadyRun(this.selectedByDefault, 300);
    });
  },
  methods: {

    // 初始加载时 以及 编排面更改配置时 触发
    loadWidget(pageStatus) {
      this.pageStatus = pageStatus;
      this.updateConfigProperty();
      this.updateConfigData();
      if (window.isLocalEnv || this.emitComponentStatus) {
        this.updateParams(pageStatus);
        !this.isRealTime && this.debounceGetData();
      }
      this.afterLoadWidget();
    },
    selectedByDefault() {
      if (!this.active && this.menuList && this.menuList.length) {
        const { recordStatus } = this.config.config.property;
        let selectLayer = this.menuList[0];
        if (recordStatus) {
          const previousSelect = storage.session.get(this.widgetInstanceId) || {};
          const previousSelectItem = this.menuList.find(item => item.id === previousSelect.id);
          selectLayer = previousSelectItem || this.menuList[0];
        }
        this.handleClick(selectLayer);
      }
    },
    handleClick(item) {
      this.executeAction('', item);
      this.active = item.id;
      const obj = {
        label: item.label,
        layersCode: item.layersCode,
      };
      storage.session.set(this.widgetInstanceId, item);
      EventBus.$emit(this.config.events[0].key, obj);
      this.emitQuery(item);
    },
    emitQuery(params) {
      const configParameters = this.config.events[1].parameters;
      const parameters = {
        [configParameters[0].key]: params,
      };
      const keys = [configParameters[0].key];
      const evtKey = this.orgConfig.events[1].key;
      const outObj = {
        [EMIT_PARAMS_OBJ]: {
          eventKey: this.config.events[1].key,
          type: 'terms',
          isSharedParameter: this.isSharedParameter,
          widgetInstanceId: this.widgetInstanceId,
          keys,
          parameters,
          componentName: 'layer-switching-3d',
          sendTime: new Date().getTime(),
        },
      };
      if (this.widgetInstanceId) {
        this.beforeEmit(outObj);
        this.emit(evtKey, outObj);
      } else {
        const ev = EventBus;
        ev.$emit(evtKey, outObj);
      }
    },
    handleResultData(result) {
      let data = result;
      if (result && result.data) {
        data = result.data;
        if (result.data.data) {
          data = result.data.data;
        }
      }

      if (!data || !data.length) {
        return;
      }
      this.menuList = data;
    },
    getChartData() {
      const { data } = this.config.config;
      if (!data.dataSourceType) {
        return;
      }

      // 如果dataSourceType为静态数据,把数据放到Vuex，发出事件，然后退出
      if (data.dataSourceType === 'staticData') {
        const layerSwitching3dRes = this.getStaticData();
        this.sendDataToConfig(layerSwitching3dRes);
        this.isNoData = !layerSwitching3dRes || !layerSwitching3dRes.length;
        if (!this.isNoData) {
          this.handleResultData(layerSwitching3dRes);
        }
        return;
      }
      this.isLoading = true;
      this.autoRefresh();
      const method = `getChartData${data.dataSourceType}`;
      const params = this.getCorrectParams(this.params, data.dataSourceType);
      dataModel[method](params, data)
        .then(layerSwitching3dRes => {
          this.isNoData = !layerSwitching3dRes || !layerSwitching3dRes.length;
          if (this.autoRefreshIsSameRes(layerSwitching3dRes)) {
            return;
          }
          this.lastParams = null;
          this.sendDataToConfig(layerSwitching3dRes);
          if (!this.isNoData) {
            this.handleResultData(layerSwitching3dRes);
          }
        })
        .finally(() => {
          this.isLoading = false;
        });
    },

    // 接收xvue发来的实时数据
    handleRealTimeCommunication(realTimeData) {
      const { datalist } = realTimeData || {};
      if (!datalist || datalist.length === 0 || !datalist[0].data || datalist[0].data.length === 0) {
        return;
      }
      const result = datalist[0].data[0];

      // api请求，拿到数据
      this.handleResultData(result);
    },

    mouseenterMenu(data) {
      this.isMouseMenu = data.id;
    },
    mouseleaveMenu() {
      this.isMouseMenu = '';
    },
    getIconConf(item, index) {
      let iconConf = item.iconStart.icon || {};
      if (item.id === this.active) {
        iconConf = item.iconStop.icon || {};
      }
      if (item.id === this.isMouseMenu) {
        iconConf = item.iconStop.icon || {};
      }
      return iconConf;
    },
    setClass(item) {
      let cname = '';
      if (item.id === this.active) {
        cname = 'layer-active';
      }
      if (item.id === this.isMouseMenu) {
        cname = 'layer-active';
      }
      return cname;
    },
  },
};
</script>
<style lang="less" scoped>
.chartMain {
  width: 100%;
  height: 100%;
  .layer-switching-3d {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow: auto;
    .layer-switching-item {
      width: 80px;
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #d1f0fe;
      font-size: 14px;
      padding-bottom: 10px;
      position: relative;
      .layer-item-bg {
        background: url('./img/layer-bg.png') no-repeat;
        background-size: 100% 100%;
        height: 80px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .ellipsis {
        position: absolute;
        bottom: 0;
        text-align: center;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .layer-active {
      color: #ffffff;
      cursor: pointer;
      .layer-item-bg {
        background: url('./img/layer-bg-hover.png') no-repeat;
        background-size: 100% 100%;
      }
    }
  }
}
</style>
